package org.example;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.example.javabean.User;
import org.example.mapper.UserMapper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private UserMapper userMapper;

    @Before
    public void setUp() throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession();
        userMapper = sqlSession.getMapper(UserMapper.class);
    }

    @After
    public void tearDown() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    @Test
    public void testFindUserById() {
        System.out.println("根据ID查询用户：" + userMapper.selectUserById(1));
    }

    @Test
    public void testFindAllUsers() {
        System.out.println("查询所有用户：");
        userMapper.selectAllUser().forEach(System.out::println);
    }

    @Test
    public void testAddUser() {
        User user = new User();
        user.setUsername("test_user");
        user.setPassword("123456");
        user.setEmail("test@example.com");
        int rows = userMapper.insertUser(user);
        sqlSession.commit();
        System.out.println("插入用户影响行数：" + rows);
    }

    @Test
    public void testModifyUser() {
        User user = userMapper.selectUserById(1);
        if (user != null) {
            user.setEmail("updated@example.com");
            int rows = userMapper.updateUser(user);
            sqlSession.commit();
            System.out.println("更新用户影响行数：" + rows);
        }
    }

    @Test
    public void testRemoveUser() {
        int rows = userMapper.deleteUser(3);
        sqlSession.commit();
        System.out.println("删除用户影响行数：" + rows);
    }

    @Test
    public void testFindUsersByCondition() {
        User condition = new User();
        condition.setUsername("test");
        System.out.println("根据条件查询用户：");
        userMapper.selectUserByCondition(condition).forEach(System.out::println);
        condition.setEmail("example");
        System.out.println("多条件查询用户：");
        userMapper.selectUserByCondition(condition).forEach(System.out::println);
    }

    @Test
    public void testFindUserWithRole() {
        System.out.println("用户及其角色信息：" + userMapper.selectUserWithRole(1));
    }

    @Test
    public void testFindAllUsersWithRoles() {
        System.out.println("所有用户及其角色信息：");
        userMapper.selectAllUserWithRole().forEach(System.out::println);
    }
}